package com.aso114.project.mvp.activity.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aso114.project.R;
import com.aso114.project.adapter.GridAdapter;
import com.aso114.project.base.BaseFragment;
import com.aso114.project.bean.BannerBean;
import com.aso114.project.bean.GridBean;
import com.aso114.project.bean.QuestionBean;
import com.aso114.project.exam.ExpositionTestActivity;
import com.aso114.project.exam.QuestionTestActivity;
import com.aso114.project.mvp.LoginSP;
import com.aso114.project.mvp.activity.BannerDetaiActivity;
import com.aso114.project.mvp.activity.NeedNoticeDetailActivity;
import com.aso114.project.mvp.model.CallBack;
import com.aso114.project.mvp.model.CommentModel;
import com.aso114.project.util.Constant;
import com.aso114.project.util.Helper;
import com.aso114.project.util.StatusBarUtil;
import com.aso114.project.util.SystemBarHelper;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;


/**
 * 须知
 *
 * @author Administrator
 */
public class MainTwoFragment extends BaseFragment implements OnItemClickListener {
    @BindView(R.id.title_left_tv)
    TextView titleLeftTv;
    Unbinder unbinder;
    @BindView(R.id.layout_title_bar_title_tv)
    TextView layoutTitleBarTitleTv;
    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.gridview)
    GridView gridview;
    Intent intent;
    @BindView(R.id.title_right_tv)
    TextView titleRightTv;
    @BindView(R.id.layout_title_bar_right_iv)
    ImageView layoutTitleBarRightIv;
    @BindView(R.id.title_top_ly)
    RelativeLayout titleTopLy;

    //定义图标数组
    private int[] imageRes = {
            R.mipmap.home_baokao_ic,
            R.mipmap.home_shij_ic,
            R.mipmap.home_kssj_ic,
            R.mipmap.home_kszl_ic,
            R.mipmap.home_bktj_ic,
            R.mipmap.home_bkcs_ic,
            R.mipmap.home_ksnr_ic,
            R.mipmap.home_tjkc_ic,
            R.mipmap.home_mdgs_ic};

    //定义图标下方的名称数组
    private String[] name = {
            "考试简介",
            "报名时间",
            "考试时间",
            "考试资料",
            "报考条件",
            "报考程序",
            "考试内容",
            "体检考察",
            "名单公示"
    };
    private List<GridBean> list;
    private GridAdapter adapter;
    private List<BannerBean> bannerList;

    Dialog dialog;

    @Override
    protected int getLayoutResourceId() {
//实现状态栏图标和文字颜色为暗色    xml文件的根布局中去添加android:fitsSystemWindows="true"
        getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        StatusBarUtil.setOPPOStatusTextColor(true, getActivity());
        return R.layout.fragmenttwo;
    }

    @Override
    protected void initView() {
        SystemBarHelper.immersiveStatusBar(getActivity());
        SystemBarHelper.setHeightAndPadding(getActivity(), titleTopLy);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(getActivity(), 0);
            SystemBarHelper.setStatusBarDarkMode(getActivity());
        }
        titleRightTv.setVisibility(View.GONE);
        layoutTitleBarRightIv.setVisibility(View.GONE);
        layoutTitleBarTitleTv.setText("须  知");
        getBanner();
        getType();
        //添加消息处理
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(getActivity(), name[position], Toast.LENGTH_LONG).show();
                intent = new Intent(getContext(), NeedNoticeDetailActivity.class);
                intent.putExtra("type", String.valueOf(position + 1));
                startActivity(intent);

            }
        });


    }

    private void getBanner() {
        CommentModel.getInstant().getAptiudeTest_banner(Constant.adutst,"2", new CallBack() {
            @Override
            public void onSuccess(Object o, boolean isSuccess, String msg) {
                Helper.gotoLogin(isSuccess);//token失效去重新登陆
                bannerList = (List<BannerBean>) o;

                System.out.println("banner数组大小===" + bannerList.size());

                initBanner();

            }

            @Override
            public void onFailure(String fail) {
                bannerList = new ArrayList<>();
                BannerBean bn = new BannerBean();

                bn.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408736304&di=a4bfe0ca275ca305834a525c18cd231d&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181120%2F9c4edc6604e84eba863c75f2e6cd7221.jpeg");
                bannerList.add(bn);
                BannerBean bn1 = new BannerBean();
                bn1.setLitpic("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543408563496&di=cbef8feab19013ac5f3b9507a62f75f7&imgtype=0&src=http%3A%2F%2Fd.ifengimg.com%2Fw600%2Fp0.ifengimg.com%2Fpmop%2F2018%2F1105%2F061500E3A7CFE1AA91524E97BEFE84D6A09FE7B7_size98_w1000_h562.jpeg");
                bannerList.add(bn1);

                System.out.println("banner数组大小===" + bannerList.size());
                initBanner();
            }
        });
    }

    private void initBanner() {
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, bannerList);
        convenientBanner.setPointViewVisible(true)//设置指示器是否可见
                //设置自动切换（同时设置了切换时间间隔）
                .startTurning(3000)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.mipmap.ej_sjkbai_ic, R.mipmap.ej_sjk_ic})
                //设置指示器的方向（左、中、右）
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置点击监听事件
                .setOnItemClickListener(this)
                //设置手动影响（设置了该项无法手动切换）
                .setManualPageable(true);
        if (bannerList.size() > 1) {
            convenientBanner.setCanLoop(true);
            convenientBanner.setPointViewVisible(true);
        } else {
            convenientBanner.setCanLoop(false);
            convenientBanner.setPointViewVisible(false);
        }
    }

    /**
     * banner item点击事件
     */
    @Override
    public void onItemClick(int position) {
        // 获取banner  type
        int type = Integer.valueOf(bannerList.get(position).getLinktype());

        switch (type) {
            case 0:// 无跳转
                break;
            case 1:// 链接
                intent = new Intent(getActivity(), BannerDetaiActivity.class);
                intent.putExtra("linkUrl",bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;
            case 2:// 题库
                final String[] id = bannerList.get(position).getLinkurl().split(",");//[考题ID，行测或申论ID，考区ID]
                View dialogview = getActivity().getLayoutInflater().inflate(
                        R.layout.loading_view, null);
                final Dialog dialog = new Dialog(getActivity(), R.style.dialogStyle);
                dialog.setContentView(dialogview, new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                dialog.getWindow().setGravity(Gravity.CENTER);
                // 设置点击外围解散
                dialog.setCanceledOnTouchOutside(true);
                dialog.setCancelable(true);//设置是否可以按退回键取消
                dialog.show();
                Constant.title_tv = "3";
                CommentModel.getInstant().get_question_bank(id[2], id[0], id[1], new CallBack() {
                    @Override
                    public void onSuccess(Object o, boolean isSuccess, String msg) {
                        dialog.cancel();
                        Helper.gotoLogin(isSuccess);//token失效去重新登陆
                        QuestionBean qdata = (QuestionBean) o;

                        EventBus.getDefault().postSticky(qdata);
                        if (Constant.adutst.equals(id[1])){//行测
                            //行测
                            intent = new Intent(getActivity(), QuestionTestActivity.class);
                            intent.putExtra(QuestionTestActivity.IS_EXAM, true);

                        }
                        if (Constant.essay.equals(id[1])){//申论
                            //申论
                            intent = new Intent(getActivity(), ExpositionTestActivity.class);

                        }
                        startActivity(intent);

                    }

                    @Override
                    public void onFailure(String fail) {
                        Helper.showToast("获取题库失败");
                        dialog.cancel();
                    }
                });
                break;
            case 3:// 页面（须知）
                intent = new Intent(getContext(), NeedNoticeDetailActivity.class);
                intent.putExtra("type", bannerList.get(position).getLinkurl());
                startActivity(intent);
                break;

        }
    }

    public class NetworkImageHolderView implements Holder<BannerBean> {
        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, BannerBean data) {
            Glide.with(getActivity()).load(data.getLitpic()).into(imageView);
        }

    }

    /**
     * gridview  的  adapter
     */
    private void getType() {
        list = new ArrayList<>();
        adapter = new GridAdapter(imageRes, name);
        gridview.setAdapter(adapter);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void addOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
            savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        SystemBarHelper.immersiveStatusBar(getActivity());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemBarHelper.immersiveStatusBar(getActivity(), 0);
            SystemBarHelper.setStatusBarDarkMode(getActivity());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.title_left_tv, R.id.layout_title_bar_title_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_tv:

                break;
            case R.id.layout_title_bar_title_tv:
                break;
        }
    }

//


}